package com.dp1.pucp.Seguridad.DAO;

import com.dp1.pucp.Modelo.Clases.Log;
import com.dp1.pucp.Modelo.Clases.Usuario;
import com.dp1.pucp.Util.HibernateUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class LogDAO {

    public static void insertarLog(Usuario usuario, String accion) {
        Log log = new Log();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            log.setUsuario(usuario);
            log.setFechaHora(new Date());
            log.setAccion(accion);
            session.saveOrUpdate(log);
            tx.commit();
        } catch (HibernateException e) {
            throw new HibernateException(e);
        } finally {
            session.close();
        }
    }

    public ArrayList<Log> listarLog() {
        ArrayList<Log> listaResultados = new ArrayList<>();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            List lista = session.createQuery("from Log order by idlog").list();
            Iterator iter = lista.iterator();
            while (iter.hasNext()) {
                Log p = (Log) iter.next();
                Hibernate.initialize(p.getUsuario());
                Hibernate.initialize(p.getAccion());
                Hibernate.initialize(p.getFechaHora());
                listaResultados.add(p);
            }
            tx.commit();
        } catch (HibernateException e) {

            throw new HibernateException(e);
        } finally {
            session.close();
            return listaResultados;
        }
    }
}
